import { CloseOutlined } from '@ant-design/icons';
import { useSize } from 'ahooks';

// import EmptyPape from '@/components/empty/EmptyPage';

import { TreeData } from '@/types/dataset';
import NewDatasetModal from './NewDatasetModal';
import { formatDataWithSeconds } from '@/utils/time';
import Tables from '@/components/tables/tables';
import EmptyTip from '@/components/EmptyTip';
import DatasetHeader from './DatasetHeader';

import {
  Button,
  Input,
  message,
  Modal,
  Space,
  Splitter,
  Table,
  Pagination,
  Typography,
} from 'antd';
import dayjs from 'dayjs';
import { useEffect, useRef, useState, useMemo } from 'react';
import { useContextSelector } from 'use-context-selector';

import datasetService from '@/api/services/datasetService';
import { Collection, DatasetListItem, MAX_NAME_LENGTH } from '@/common';
import AuthModal from '@/components/auth-modal/auth-modal';
import { Search, Empty } from '@/components/eai-design';
import { SvgIcon } from '@/components/icon';
import ImportTipsModals from '@/components/modals/ImportTipsModals';
import Modals from '@/components/modals/Modals';
import useWindowWidth from '@/hooks/event/use-window-width';
import useModal from '@/hooks/use-modal/useModal';
import DeleteConfirmModal from '@/pages/datasets/components/DeleteConfirmModal';
import { useRouter, useParams } from '@/router/hooks';
import { useDatasetStore } from '@/store/datasetStore';
import { useUserInfo } from '@/store/userStore';
import { ApiDatasetEvent } from '@/types/api';
import { Size } from '@/types/common';
import { convertHeaderAuthToFormData, formatAuthData, formatAuthConfig } from '@/utils/auth';
import { isValidURL } from '@/utils/common';

import { ApiManageContext } from '../context';
import '../styles/api.scss';

import type { TableColumnsType } from 'antd';

const { Text } = Typography;

interface AuthDefaultData {
  appId?: string;
  headerAuth?: object;
}

interface Props {
  datasets: DatasetListItem[];
  groupId: string | undefined;
  managers: any;
  approves: any;
  isAdmin: boolean;
  isPermit: boolean;
  parentSize: Size;
  loading: boolean;
  total: number;
  pageSize: number;
  page: number;
  searchValue?: string;
  setSearchValue?: (value: string) => void;
  onItemClicked?: (item: DatasetListItem | undefined) => void;
  handlePageChange?: (page: number, pageSize: number) => void;
}
interface FailDataType {
  desc: string;
  error: string;
  method: string;
  path: string;
}

interface ImportingInfo {
  detail?: FailDataType[];
  [key: string]: any;
}

const ApiTable = ({
  datasets,
  isAdmin,
  isPermit,
  parentSize,
  loading,
  onItemClicked,
  handlePageChange,
  groupId,
  managers,
  total,
  approves,
  pageSize,
  page,
  searchValue,
  setSearchValue,
}: Props) => {
  const { loadAllDatasets1 } = useDatasetStore();
  const [parentId, setParentId] = useState<string | null>('');
  const modal = useModal('input');
  const [renameModalVisible, setRenameModalVisible] = useState(false);
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [selectedRows, setSelectedRows] = useState<Collection[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [newName, setNewName] = useState('');
  const [isBatchDelete, setIsBatchDelete] = useState(false);
  const [editItem, setEditItem] = useState<Collection | undefined>(undefined);
  const { isPc } = useWindowWidth();
  const { event$ } = useContextSelector(ApiManageContext, (s) => s);
  const { role } = useUserInfo();
  const { appId = '' } = useParams() as { appId: string };
  const [dataList, setDataList] = useState<DatasetListItem[]>([]);
  const [isImporting, setIsImporting] = useState(false);
  const [importTipsModalVisible, setImportTipsModalVisible] = useState(false);
  const [importingInfo, setImportingInfo] = useState<ImportingInfo>({});
  const [syncDataVisible, setSyncDataVisible] = useState(false);
  const [failDataVisible, setFailDataVisible] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [apiUrl, setApiUrl] = useState('');
  const ref = useRef<HTMLDivElement>(null);
  const size = useSize(ref);
  const [selectedDataset, setSelectedDataset] = useState<DatasetListItem | undefined>(undefined);
  const [authConfig, setAuthConfig] = useState<any>(null);
  const [globalAuthConfig, setGlobalAuthConfig] = useState<any>(null);
  const [globalAuthData, setGlobalAuthData] = useState<any>(null);
  const [authData, setAuthData] = useState<string>('');
  const [openAuthType, setOpenAuthType] = useState<string>('');
  const [headerAuth, setHeaderAuth] = useState<any>({});
  // 失败数据分页相关状态
  const [failPageNum, setFailPageNum] = useState(1);
  const [failPageSize, setFailPageSize] = useState(10);
  const [failDataTotal, setFailDataTotal] = useState(0);
  const { setNewApiModalVisible } = useContextSelector(ApiManageContext, (s) => s);

  const [newDatasetModalVisible, setNewDatasetModalVisible] = useState(false);
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: Collection[]) => {
      console.log(selectedRowKeys, selectedRows);
      setSelectedRows(selectedRows);
      setSelectedRowKeys(selectedRowKeys);
    },
    selectedRowKeys,
  };
  const failColumns: TableColumnsType<FailDataType> = [
    { title: 'URL', dataIndex: 'path', key: 'path', ellipsis: true },
    { title: '方法', dataIndex: 'method', key: 'method', ellipsis: true },
    { title: '描述', dataIndex: 'desc', key: 'desc', ellipsis: true },
    { title: '原因', dataIndex: 'error', key: 'error', ellipsis: true },
  ];

  // 前端分页逻辑
  const getFailDataWithPagination = useMemo(() => {
    const failData = importingInfo?.detail || [];
    const startIndex = (failPageNum - 1) * failPageSize;
    const endIndex = startIndex + failPageSize;
    return failData.slice(startIndex, endIndex);
  }, [failPageNum, failPageSize, importingInfo?.detail]);

  // 处理失败数据分页变化
  const handleFailPageChange = (page: number, pageSize: number) => {
    console.log(page, pageSize, 'page, pageSize');
    if (pageSize != failPageSize) {
      setFailPageNum(1);
    } else {
      setFailPageNum(page);
    }
    setFailPageSize(pageSize);
  };

  // 当失败数据弹窗打开时，重置分页状态
  useEffect(() => {
    if (failDataVisible) {
      setFailPageNum(1);
      setFailPageSize(10);
      const failData = importingInfo?.detail || [];
      setFailDataTotal(failData.length);
    }
  }, [failDataVisible, importingInfo?.detail]);
  const columns = [
    {
      // title: <div>全部文档 ({total})</div>,
      title: '业务办理接口',
      dataIndex: 'name',
      key: 'name',
      render: (name: string) => (
        <div className="items-cente flex w-full gap-2">
          <SvgIcon icon="dataset-icon-jianbian" size={20} />
          <Text ellipsis={{ tooltip: name }}>{name}</Text>
        </div>
      ),
    },
    {
      title: '数据源',
      dataIndex: 'openapiUrl',
      key: 'openapiUrl',
      render: (openapiUrl: string) => (
        <Text ellipsis={{ tooltip: openapiUrl }}>{openapiUrl || '-'}</Text>
      ),
    },
    {
      title: '时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      render: (updateTime: string) => (
        <span>{dayjs(updateTime).format('YYYY-MM-DD HH:mm:ss')}</span>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: '100px',
      render: (_, record: DatasetListItem) => (
        <Space size="small">
          {isAdmin ? (
            <div className="flex cursor-pointer items-center gap-2 text-@brand-color">
              <Button
                type="text"
                style={{
                  background: 'none',
                  border: 'none',
                  font: 'inherit',
                }}
                onClick={(e) => {
                  e.stopPropagation();
                  setEditItem(record);
                  setNewDatasetModalVisible(true);
                }}
              >
                <SvgIcon icon="singleedit" />
                修改
              </Button>

              <Button
                type="text"
                danger
                style={{
                  background: 'none',
                  border: 'none',
                  font: 'inherit',
                }}
                onClick={(e) => {
                  e.stopPropagation();
                  setEditItem(record);
                  setDeleteModalVisible(true);
                }}
              >
                <SvgIcon icon="deltongbu" />
                删除
              </Button>
            </div>
          ) : (
            '-'
          )}
        </Space>
      ),
      // onCell: () => ({ style: { width: '300px' } }),
    },
  ];

  const getDatasets = async () => {
    try {
      // 获取业务办理数据
      const res: any = await loadAllDatasets1({
        parentId,
        page,
        page_size: pageSize,
        offset: (page - 1) * pageSize,
        searchText: '',
        groupId: '',
        isPage: true,
        app_id: appId || '67fcd7c1de9ddb56bea37b6c', // 必填
        dataset_type: 'business',
      });
      setDataList(res.list);
      // setTotal(res.total);
    } catch (error) {
    } finally {
    }
  };

  const handleConfirmNewDataset = async (name: string, headerAuth: object) => {
    const newName = name?.trim();
    if (!newName) {
      message.error('请输入名称');
      return;
    }
    await datasetService[`${editItem?.id ? 'updateKnowledgeBase' : 'createKnowledgeBase'}`]({
      dataset_id: editItem?.id,
      parentId: null,
      app_id: appId,
      type: 'business',
      name: newName,
      intro: '',
      avatar: '/imgs/dataset/dataset.svg',
      vectorModel: '',
      agentModel: '',
      openapiUrl: '',
      dataset_tags: [''],
      groupId,
      assessor: approves.map((item) => item?.id),
      administrator: managers.map((item) => item?.id),
      uploader: [],
      dataset_type: 'business',
      headerAuth,
    });
    message.success('修改成功');
    setNewDatasetModalVisible(false);
    setEditItem(undefined);
    event$?.emit(ApiDatasetEvent.REFRESHDATASET);
  };

  const paginationConfig = {
    current: page,
    pageSize,
    pageSizeOptions: undefined,
    total,
    onChange: handlePageChange,
  };

  const clearSelections = () => {
    setSelectedRows([]);
    setSelectedRowKeys([]);
  };

  const rename = async () => {
    const newNameRename = newName.trim();
    if (!newNameRename) {
      message.error('名称不能为空');
      return;
    }
    if (newNameRename.length > MAX_NAME_LENGTH) {
      message.error(`名称长度不能超过 ${MAX_NAME_LENGTH} 字符`);
      return;
    }
    if (!editItem) {
      return;
    }
    await datasetService.datasetUpdate({
      id: editItem?._id,
      name: newNameRename, // 假设 newName 是新的名称
    });
    message.success('修改名称成功！');
    event$?.emit(ApiDatasetEvent.REFRESHDATASET);
    setRenameModalVisible(false);
    setEditItem(undefined);
  };

  const handleDeleteConfirm = async () => {
    if (deleting) return;
    setDeleting(true);
    if (isBatchDelete) {
      const promises = selectedRows.map(async (row) => {
        await datasetService.datasetDelete({
          id: [row?.id],
          reviewStatus: 'drop',
          app_id: appId,
        });
      });

      await Promise.all(promises);
    } else {
      if (!editItem) {
        return;
      }
      await datasetService.datasetDelete({
        id: [editItem?.id],
        reviewStatus: 'drop',
        app_id: appId || '67fcd7c1de9ddb56bea37b6c',
      });
    }
    message.success('删除成功！');
    setDeleteModalVisible(false);
    setEditItem(undefined);
    setIsBatchDelete(false);
    setDeleting(false);
    clearSelections();
    event$?.emit(ApiDatasetEvent.REFRESHDATASET);
  };

  const handleBatchDelete = async () => {
    setIsBatchDelete(true);
    setDeleteModalVisible(true);
  };

  const handleRowClick = (record: DatasetListItem) => {
    onItemClicked && onItemClicked(record);
  };

  useEffect(() => {
    setDataList(datasets);
  }, [datasets]);

  const handleNewDataset = () => {
    setNewDatasetModalVisible(true);
  };
  useEffect(() => {
    getBusinessAuth();
  }, []);

  const handleSetting = async (type: string) => {
    setOpenAuthType(type);
    if (type == 'default') {
      await getBusinessAuth();
    } else {
      console.log(authData, '----authData');
    }
    modal.input.open();
  };

  const getBusinessAuth = () => {
    datasetService
      .getBusinessAuth(appId)
      .then((res) => {
        setAuthConfig(res?.headerAuth || {});
        setAuthData(formatAuthData(res?.headerAuth));
        setGlobalAuthData(formatAuthData(res?.headerAuth));
        setGlobalAuthConfig(res?.headerAuth || {});
        setHeaderAuth(res?.headerAuth || {});
      })
      .catch((error) => {
        console.error('获取工具列表失败:', error);
      });
  };

  const handleAuthSubmit = (value: object) => {
    if (openAuthType == 'default') {
      const params = {
        headerAuth: formatAuthConfig(value),
      };
      datasetService
        .updateBusinessAuth(appId, params as AuthDefaultData)
        .then((res) => {
          modal.input.close();
          message.success('配置成功');
          getBusinessAuth();
        })
        .catch((error) => {
          console.error('获取工具列表失败:', error);
        });
    } else {
      setAuthConfig(value);
      setAuthData(formatAuthData(value));
      setHeaderAuth(formatAuthConfig(value));
      modal.input.close();
    }
  };

  const closeSyncDataModal = () => {
    setSyncDataVisible(false);
    setApiUrl('');
  };

  const confirmImportApi = async () => {
    if (!isAdmin) {
      message.error('没有操作权限！');
      return;
    }
    if (!apiUrl) {
      message.warning('请输入同步地址！');
      return;
    }
    if (!isValidURL(apiUrl)) {
      console.log('-----2', isValidURL(apiUrl));
      message.warning('请输入正确的同步地址！');
      return;
    }
    console.log(headerAuth, '----headerAuth');

    try {
      setImportingInfo({});
      setIsImporting(true);
      setSyncDataVisible(false);
      setImportTipsModalVisible(true);
      const res = await datasetService.createKnowledgeBase({
        type: 'business',
        dataset_type: 'business',
        avatar: '/imgs/dataset/dataset.svg',
        name: apiUrl,
        intro: '',
        vectorModel: 'embedding-model',
        agentModel: 'vllm-chat-model',
        parentId: null,
        openapiUrl: apiUrl,
        app_id: appId, // 必填
        groupId,
        assessor: approves.map((item) => item?.id),
        administrator: managers.map((item) => item?.id),
        headerAuth,
      });
      setImportingInfo(res);
      message.success('同步成功');
      setSelectedDataset(undefined);
      event$?.emit(ApiDatasetEvent.REFRESHDATASET);
    } catch (error) {
      console.error(error);
    } finally {
      setIsImporting(false);
    }
  };

  return (
    <>
      {/* {loading && <CircleLoading />} */}
      <div className="relative flex h-full flex-col gap-4 overflow-y-auto">
        <div className="z-15 left-0 top-2 flex w-full justify-between">
          <div className="my-auto w-[240px]">
            <Search
              placeholder="请输入内容"
              onChange={(e) => {
                setSearchValue && setSearchValue(e.target.value);
                handlePageChange && handlePageChange(1, pageSize);
              }}
              value={searchValue}
              suffix={<SvgIcon icon="work-ic6" size={16} />}
            />
          </div>

          {isAdmin && (
            <Space className="ml-auto">
              <>
                <Button
                  type="text"
                  style={{ border: '1px solid #1B6DFA' }}
                  onClick={() => {
                    handleSetting('default');
                  }}
                >
                  <SvgIcon icon="ic_setting_blue" size={16} />
                  鉴权配置
                </Button>
                <Button
                  type="text"
                  className="ml-2"
                  style={{ border: '1px solid #1B6DFA' }}
                  onClick={() => {
                    setApiUrl('');
                    setAuthData(globalAuthData);
                    setSyncDataVisible(true);
                  }}
                >
                  <SvgIcon icon="retry" size={16} />
                  同步业务办理接口
                </Button>
              </>
              <DatasetHeader
                selectedItem={selectedDataset}
                isAdmin={isAdmin}
                isPermit={isPermit}
                parentSize={size ?? { width: 0, height: 0 }}
                onDeleteClicked={() => {
                  setDeleteModalVisible(true);
                }}
                onNewClicked={() => {
                  setNewApiModalVisible(true);
                }}
                onNewDatasetClicked={handleNewDataset}
              />
            </Space>
          )}
        </div>
        <Tables
          rowClassName="bg-[#fff] custom-scrollbar"
          className="custom-scrollbar"
          dataSource={dataList}
          columns={columns}
          rowSelection={isAdmin ? rowSelection : {}}
          rowKey="id"
          onRow={(record) => {
            return {
              onClick: () => handleRowClick(record), // 点击行时触发
            };
          }}
          pagination={false}
          // rowBgClassName="bg-[#F6F7FB]"
          // scroll={scroll}
          paginationProps={paginationConfig}
          locale={{
            emptyText: (
              <div style={{ textAlign: 'center', color: '#999' }}>{!loading && <Empty />}</div>
            ),
          }}
        />
      </div>

      {selectedRows.length > 0 && isAdmin && (
        <div
          className="animated-div"
          style={{
            position: 'fixed',
            bottom: '5%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            background: '#474C5F',
            borderRadius: '50px',
          }}
        >
          <Space className="ml-2 mr-2" style={{ height: '45px' }}>
            <Button
              style={{ color: '#fff' }}
              type="text"
              icon={<CloseOutlined />}
              onClick={clearSelections}
            />
            <span className="whitespace-nowrap text-nowrap text-xs" style={{ color: '#8E93A4' }}>
              已选 {selectedRows.length} 项
            </span>
            <Splitter />

            <Button style={{ color: '#fff' }} type="text" onClick={handleBatchDelete}>
              删除
            </Button>
          </Space>
        </div>
      )}

      <Modals
        title="同步业务办理接口"
        open={syncDataVisible}
        onCancel={closeSyncDataModal}
        okText="确定"
        cancelText="取消"
        maskClosable={false}
        centered
        onOk={confirmImportApi}
      >
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '60px',
          }}
        >
          <Input
            allowClear
            placeholder="请输入业务办理接口地址"
            value={apiUrl}
            onChange={(e) => setApiUrl(e.target.value)}
          />
        </div>
        <div>
          <div className="mb-2 text-[var(--text-secondary)]">鉴权配置</div>
          <div className="flex h-11 w-full items-center justify-between rounded-md bg-[var(--fill-quinary)] px-3 text-sm font-normal text-text-5">
            <div>{authData || '无'}</div>
            <div
              className="flex cursor-pointer items-center gap-1 text-sm font-normal text-[var(--geekblue-6)]"
              onClick={() => {
                handleSetting('sync');
              }}
            >
              <SvgIcon icon="manage" size={16} />
              设置
            </div>
          </div>
        </div>
      </Modals>

      <Modal
        title={<div style={{ textAlign: 'center', width: '100%' }}>重命名</div>}
        open={renameModalVisible}
        onCancel={() => {
          setRenameModalVisible(false);
        }}
        okText="确定"
        cancelText="取消"
        closable={false}
        width={300}
        centered
        footer={
          <div style={{ textAlign: 'center' }}>
            <Space size={56}>
              <Button
                onClick={() => {
                  setRenameModalVisible(false);
                }}
              >
                取消
              </Button>
              <Button type="primary" onClick={rename}>
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '60px',
          }}
        >
          <Input value={newName} onChange={(e) => setNewName(e.target.value)} />
        </div>
      </Modal>

      <DeleteConfirmModal
        visible={deleteModalVisible}
        text="确定要删除吗？"
        onCancel={() => {
          setDeleteModalVisible(false);
        }}
        onConfirm={handleDeleteConfirm}
        onConfirmText={deleting ? '删除中' : `删除`}
      />
      <NewDatasetModal
        title={`${editItem?.id ? '编辑' : ''}业务办理接口集`}
        editType={editItem?.id ? 'update' : 'create'}
        onConfirm={handleConfirmNewDataset}
        onCancel={() => {
          setNewDatasetModalVisible(false);
          setEditItem(undefined);
        }}
        updateDataset={editItem}
        open={newDatasetModalVisible}
        defaultAuthConfig={globalAuthConfig}
      />
      <AuthModal
        open={modal.input.isOpen}
        onCancel={modal.input.close}
        onSubmitOk={handleAuthSubmit}
        title="鉴权配置"
        defaultValue={convertHeaderAuthToFormData(authConfig)}
        zIndex={1001}
        infoMessage={
          openAuthType == 'default'
            ? '在新建数据集及接口会默认填充相关鉴权配置，修改不做列表变更'
            : ''
        }
      />
      <ImportTipsModals
        isImporting={isImporting}
        open={importTipsModalVisible}
        importingInfo={importingInfo}
        className="h-[200px]"
        onFailInfo={() => {
          setImportTipsModalVisible(false);
          setFailDataVisible(true);
        }}
        onReset={() => {
          confirmImportApi();
        }}
        onCancel={() => {
          setImportTipsModalVisible(false);
        }}
        footer={null}
        closable={false}
      />
      <Modals
        className="!w-[665px]"
        title="未接入接口详情"
        open={failDataVisible}
        okText="确定"
        maskClosable={false}
        footerCancelHidden
        centered
        onOk={() => {
          setFailDataVisible(false);
        }}
        onCancel={() => {
          setFailDataVisible(false);
        }}
      >
        <Table<FailDataType>
          columns={failColumns}
          dataSource={getFailDataWithPagination}
          pagination={false}
          rowKey={(record, index) => `${record.path}-${index}`}
        />
        <div className="flex items-center justify-between py-6">
          <div className="pagination-total text-text-4">
            共<span className="mx-2">{failDataTotal || 0}</span>项数据
          </div>

          <Pagination
            defaultCurrent={1}
            simple
            current={failPageNum}
            pageSize={failPageSize}
            total={failDataTotal}
            onChange={handleFailPageChange}
          />
        </div>
      </Modals>
    </>
  );
};

export default ApiTable;
